<template>
  <div class="login">
    <el-form class="login-form" ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
       <h2>登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" @click="onSubmit" :loading="isLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { login } from '@/services/user'
import { Form } from 'element-ui'

export default Vue.extend({
  name: 'LoginIndex',
  data () {
    return {
      form: {
        phone: '',
        password: ''
      },
      isLogin: false,
      rules: {
        phone: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur'
          },
          {
            pattern: /^1\d{10}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 16,
            message: '长度在 6-16 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      this.isLogin = true
      try {
        // 验证表单
        await (this.$refs.form as Form).validate()
        // 提交表单
        const { data } = await login(this.form)
        // 处理请求结果
        if (data.state !== 1) {
          this.$message.error(data.message)
        } else {
          // 登录成功后，记录登录状态
          this.$store.commit('setUser', data.content)
          // 路由跳转
          this.$router.push(this.$route.query.redirect as string || '/')
          this.$message.success('登录成功')
        }
      } catch (error) {
        this.$message.error('登录失败')
      }

      this.isLogin = false
    }
  }
})

</script>

<style lang="scss">
  .login {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-content: center;

    .login-form {
      width: 300px;
      height: 35vh;
      background: #fff;
      padding: 20px;
      border-radius: 5px;
    }

    .login-btn {
      width: 100%;
    }
  }
</style>
